
<template>
  <div class="dish-management" style="margin-top: 50px">
    <div>
      3. 菜品列表
    </div>
    <!-- 1. 搜索框 -->
    <div class="search-bar" style= "display: flex;margin-left: 20px ">

      <!-- 2. 下拉列表 -->
      <!--分类搜索-->
<div>
  <select v-model="selectedCategory" style="margin-left: 20px">
    <option value="">全部分类</option>
    <option v-for="category in uniqueCategories" :key="category" :value="category">
      {{ category }}
    </option>
  </select>
</div>

      <div>
        <input v-model="searchQuery" type="text" placeholder="请输入菜品名称" />
        <button @click="searchDishes">搜索</button>
      </div>

    </div>
    <!--菜品展示及点单-->
    <div style="display: flex;width: 1400px">

      <div class="dish-list" style="width: 800px;display: flex; flex-wrap: wrap;">

<!--height: 150px;border: skyblue 2px solid; -->
          <div class="dish-item" style="width: 150px; margin: 20px;text-align: center" v-for="dish in filteredDishes" :key="dish.did" @click="addToCart(dish)" >
           <div>
<!--             -->
             <img style="width: 150px;height: 150px" :src="'http://localhost:8080' + dish.dimage"/>
             <span>{{ dish.dname }}</span>&nbsp;&nbsp;
             <span style="color: skyblue">{{dish.dprice}}元</span>
           </div>
           <!-- <div>

            </div>
            <div>

            </div>-->
          </div>
        </div>

<!--     4. 已选菜品列表-->

        <div class="selected-dishes">
          <h3>已选菜品</h3>
          <ul>
            <li v-for="(item,index) of selectedDishes" :key="index" style="margin: 10px">
              {{ item.dishName }}
              {{item.quantity}}份
              {{(item.quantity)*(item.price)}}
              <el-button  @click="delCart(item.cartId)">移除</el-button>
            </li>
          </ul>
        <div>
            {{totalprice}}
      </div>
        <button @click="billing">结算</button>
      </div>

      <!--添加用户信息对话框-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="customer">
          <el-form-item label="顾客姓名" :label-width="formLabelWidth">
            <el-input autocomplete="off" v-model="customer.name"></el-input>
          </el-form-item>
          <el-form-item label="顾客手机号" :label-width="formLabelWidth">
            <el-input autocomplete="off" v-model="customer.phone"></el-input>
          </el-form-item>
          <el-form-item label="顾客邮箱号" :label-width="formLabelWidth">
            <el-input autocomplete="off" v-model="customer.email"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer cf">
          <el-button type="primary" @click="saveDate">保 存</el-button>
        </div>
      </el-dialog>



    </div>
<!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { listDish,getDish, delDish, addDish, updateDish } from "@/api/project/dish";
import { addDishList,insertCustomerMessage,insertCustomerTableMessage,selectAllByTableId,delCart,insertOrder,getUId} from "@/api/project/cart";


export default {
  data() {
    return {
      //总价
      totalprice:'',
      //接受的桌台id
      tableId:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品表格数据
      dishList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeDCreattime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        did: null,
        dname: null,
        dprice: null,
        dimage: null,
        dintrodoce: null,
        dType: null,
        dCreattime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      searchQuery: '',
      selectedCategory: '',
      dishes: [],
      categories: [],
      selectedDishes: [],

      //添加用户信息对话框显隐性
      dialogFormVisible:false,
      formLabelWidth: '120px',
      uid:'',
      //顾客信息
      customer:{
        id:null,
        name:null,
        phone:null,
        email:null,
        createtime:null,
        storageMoney:null,
        points:null,
        vipId:null,
        orderId:null,
        orderListId:null,
      }


    };
  },
  computed: {
    filteredDishes() {
      return this.dishList.filter(dish => {
        const nameMatch = dish.dname.includes(this.searchQuery);
        const categoryMatch =!this.selectedCategory || dish.dType === this.selectedCategory;
        return nameMatch && categoryMatch;
      });
    },
    uniqueCategories() {
      const uniqueTypes = new Set();
      this.dishList.forEach(dish => uniqueTypes.add(dish.dType));
      return [...uniqueTypes];
    }
  },
  created() {
    this.getList();

      //如果路由参数存在
    const tId = this.$route.query.tableId
    const customer = this.$route.query.customer
        this.tableId = tId;
        this.customer = customer;
    this.refreshCart();

  },
  methods: {
    //获取uid
    getUid(){
      getUId(this.queryParams).then(response=>{
        console.log(response)
        this.uid=response.data;
      })
    },
    //删除方法
    delCart(cartID1){
      const cartId= cartID1;
      console.log(cartId)
      delCart(cartId).then(response=>{
        console.log(response);
        this.refreshCart();
      })
    },
    //刷新购物车
    refreshCart(){
      const tableId= this.tableId;
      selectAllByTableId(tableId).then(response=>{
        this.selectedDishes=response;
        console.log(response);
        if (response[0]!=null){
          this.totalprice=this.totalPrice();
        }
      })

    },

    addToCart(dish) {
      // 准备要发送给后端的数据
      const cart= {
          dishId: dish.did,
          dishName: dish.dname,
          price: dish.dprice, // 这里假设价格固定为 2，你可以根据实际情况调整
          quantity: 1 ,// 这里假设数量固定为 2，你可以根据实际情况调整
        tableId: this.tableId // 这里假设 tableId 固定为 1，你可以根据实际情况调整
      };
      console.log(this.tableId)
      addDishList(cart).then(response => {
        if (response.code === 200) {
          // 添加成功后的提示或其他操作
          console.log('添加到购物车成功');
        this.refreshCart();
        } else {
          // 添加失败后的提示或其他操作
          console.log('添加到购物车失败');
        }
      }).catch(error => {
        // 处理错误
        console.log('添加到购物车时发生错误', error);
      });
    },


    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDCreattime && '' != this.daterangeDCreattime) {
        this.queryParams.params["beginDCreattime"] = this.daterangeDCreattime[0];
        this.queryParams.params["endDCreattime"] = this.daterangeDCreattime[1];
      }
      listDish(this.queryParams).then(response => {
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    //结算按钮
    billing(){
      // this.dialogFormVisible=true;
      this.saveDate();
    },
    //结算按钮之后所进行的操作
    saveDate(){
      insertCustomerMessage(this.customer).then(response => {
        if (response.code === 200){
          this.getUid();
          const tableId = this.tableId;
          insertCustomerTableMessage(tableId).then(response => {
            if (response.code===200){
              this.settleAccounts();
            }
          });
        }
      });
    },

// cart传给order
    settleAccounts() {
      // const userid = prompt('请输入用户id');
      const userName = this.uid;
      if (userName) {
        // 获取 tableId
        const tableId = this.tableId;
        // 通过 tableId 查询 cart 表获取菜品信息
        selectAllByTableId(tableId).then(cartItems => {
          // 创建 order 表数据对象
          const orderData = {
            userId: userName,
            tableId: tableId,
            dishIds: cartItems.map(item => item.dishId),
            dishNums: cartItems.map(item => item.quantity),
            totalPrice: this.totalprice
          };
          console.log(11111111111)
          console.log(orderData)
          // 调用插入订单的 API 函数
          insertOrder(orderData).then(response => {
            console.log(response);
            // 清空购物车
            this.totalprice='';
            this.getList();
            this.$modal.msgSuccess("结账成功");
            this.selectedDishes = [];
          }).catch(error => {
            console.log('插入订单时发生错误', error);
          });
        });
      }


    },
    //提交给订单
    // addToOrder(){
    //   let order ={userId:1,totalprice:this.totalprice, dishes:this.selectedDishes,tableId:this.tableId};
    //   addToOrder(order).then(response=>{
    //   })
    // },
    searchDishes() {
      // 可以在这里添加更多的搜索逻辑
    },
  //  计算总价
    totalPrice(){
      let totalPrice=0;
      for(let i=0;i<this.selectedDishes.length;i++){
        totalPrice=totalPrice+this.selectedDishes[i].price*this.selectedDishes[i].quantity
      }
      return totalPrice;
    }
  },
};
</script>


<style scoped>
  .dish-management {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.search-bar, .category-dropdown, .dish-list, .selected-dishes {
  margin-bottom: 16px;
}

.dish-list ul, .selected-dishes ul {
  list-style-type: none;
  padding: 0;
}

.dish-list li, .selected-dishes li {
  cursor: pointer;
  padding: 8px;
  border: 1px solid #ccc;
  margin-bottom: 8px;
}

.dish-list li:hover, .selected-dishes li:hover {
  background-color: #f0f0f0;
}
/*span {
  font-size: 25px;
  line-height: 80px;
  padding-left: 25px;
  color: rgba(0, 0, 0, 0.1);
}*/
</style>
